<template>
  <sv-page>
    <view class="lib">
      <!-- banner -->
      <tn-swiper v-if="libData?.banner?.length > 0" :data="libData?.banner"
        width="100%" height="380" indicator indicator-type="dot" autoplay loop>
        <template #default="{ data, active }">
          <view class="swiper-data animation" :class="[{ active }]">
            <image class="image" :src="data" mode="aspectFill" />
          </view>
        </template>
      </tn-swiper>
      <!-- 头部介绍内容 -->
      <view
        class="header padding flex flex-direction justify-between tn-shadow">
        <view class="text-xxl text-bold">{{ libData.lib_name }}</view>
        <view class="text-xl text-gray">{{ libData.lib_title }}</view>
        <view class="text-df text-grey flex align-center">
          <view class="flex-sub">
            <text class="text-lg text-red">{{ libData.sell_num }}</text>
            人已购买
            <text>丨&nbsp;</text>
            <text class="text-lg text-red">{{ libData.fav_num }}</text>
            人已收藏
          </view>
          <uni-fav circle :checked="isFav" @click="onFavThrottle" />
        </view>
      </view>
      <!-- 主体内容 -->
      <view class="main margin-top tn-shadow st-uv-collapse">
        <uv-collapse :value="collapseValue" :border="false">
          <uv-collapse-item title="介绍" name="intro" :border="false">
            <text>{{ libData.intro }}</text>
          </uv-collapse-item>
          <uv-collapse-item title="适用范围" name="befit" :border="false">
            <text>{{ libData.befit }}</text>
          </uv-collapse-item>
          <uv-collapse-item title="题库来源" name="origin" :border="false">
            <text>{{ libData.origin }}</text>
          </uv-collapse-item>
        </uv-collapse>
      </view>
      <!-- 概览 -->
      <view class="overview margin-top"></view>
      <!-- 底部 -->
      <view class="footer">
        <view class="cu-bar tabbar border shop foot">
          <view style="width: 46%" class="padding-left-sm">
            <text class="text-price text-orange"
              style="font-size: 40rpx">{{ money }}</text>
            <template v-if="money < libData.price">
              <text class="text-df text-green">丨</text>
              <text class="text-price text-df text-red text-delete">
                {{ libData.price }}
              </text>
            </template>
            <text class="text-xs text-green padding-left-xs"
              v-if="isBuy">已购买</text>
          </view>
          <view class="btn-group">
            <button class="cu-btn round shadow-blur"
              :class="[isFav ? 'bg-blue' : 'bg-grey']" @click="onFavThrottle">
              {{ isFav ? '取消收藏' : '添加收藏' }}
            </button>
            <button class="cu-btn bg-red round shadow-blur" @click="onStart">
              {{ isBuy ? '开始练习' : '立即购买' }}
            </button>
          </view>
        </view>
      </view>
    </view>
  </sv-page>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { libList } from '@/service/api/exam'
import { buyLibAdd, buyLibList, favLibAdd, favLibDelete, favLibList } from '@/service/api/record'
import { judgeLogin } from '@/utils/sys'
import { store } from '../../uni_modules/sv-id-pages/common/store'
import { throttle } from 'lodash'
import { useSysStore } from '../../store/sys'

const libData = ref({
  lib_id: '',
  lib_name: '',
  lib_title: '',
  sell_num: 0,
  fav_num: 0,
  price: 0,
  discounts: 10,
  intro: '',
  befit: '',
  origin: '',
  banner: [],
  comment: '',
  icon: '',
  profession: '',
  total: 0
})

const collapseValue = ref(['intro', 'befit', 'origin'])

const isFav = ref(false)
const isBuy = ref(false)
const money = computed(() => {
  const { price, discounts } = libData.value
  let moneyNum
  // 计算折扣后的价格：discounts大于1时为数值优惠，大于0小于1时为比例折扣
  if (discounts > 1) {
    // 数值优惠
    moneyNum = price - discounts
  } else if (discounts >= 0 && discounts <= 1) {
    // 比例折扣 (0免费/1原价)
    moneyNum = (price * discounts).toFixed(2)
  } else {
    moneyNum = price
  }
  // 优惠力度减至0或以下，则免费
  if (moneyNum < 0) moneyNum = 0

  return moneyNum
})

async function handleInit() {
  const favLibRes = await favLibList({ user_id: store.userInfo._id })
  isFav.value = favLibRes.data?.some((item) => item.lib_id == libData.value.lib_id)

  const buyLibRes = await buyLibList({ user_id: store.userInfo._id })
  isBuy.value = buyLibRes.data?.some((item) => item.lib_id == libData.value.lib_id)

  // console.log('==== LibRes :', favLibRes.data, buyLibRes.data)
}

onLoad(async (options) => {
  await getLibById(options.lib_id)
  await handleInit()
})

async function getLibById(lib_id) {
  const libRes = await libList({ lib_id })
  libData.value = libRes.data[0]

  // 鉴于collapse在默认展开时会出问题：第一次进入页面是高度不会自适应，故此处需要手动展开一下
  collapseValue.value = ['intro', 'befit', 'origin']
}

// 收藏
function onFav() {
  // 判断登录
  const hasLogin = judgeLogin()
  // 未登录不予收藏
  if (!hasLogin) return

  isFav.value = !isFav.value
  if (isFav.value) {
    // 添加收藏
    favLibAdd({
      user_id: store.userInfo._id,
      lib_id: libData.value.lib_id
    })
  } else {
    // 取消收藏
    favLibDelete({
      user_id: store.userInfo._id,
      lib_id: libData.value.lib_id
    })
  }
}
// 收藏节流
const onFavThrottle = throttle(onFav, 1600)

// 开始联系/购买
function onStart() {
  // 判断登录
  const hasLogin = judgeLogin()
  // 未登录不予收藏
  if (!hasLogin) return

  if (isBuy.value) {
    // 开始答题 - 注意tabbar页面路径后不能带参数
    // 这里需要将题库的lib_id通过pinia持久化缓存
    useSysStore().setConfig({
      curTabbarRoute: '/pages/practice/practice',
      examingLib: libData.value,
    })
    uni.switchTab({
      url: '/pages/practice/practice'
    })
  } else {
    uni.showModal({
      title: '购买提示',
      content: `是否购买${libData.value.lib_name}`,
      showCancel: true,
      success: async ({ confirm }) => {
        if (confirm) {
          await buyLibAdd({
            user_id: store.userInfo._id,
            lib_id: libData.value.lib_id
          })
          isBuy.value = true
        }
      }
    })
  }
}
</script>

<style lang="scss">
.lib {
  .header {
    height: 240rpx;

    @include useTheme {
      background-color: getTheme('sv-background-highlight-color');
    }
  }

  .main,
  .overview {
    @include useTheme {
      background-color: getTheme('sv-background-highlight-color');
    }
  }

  .footer {
    .cu-bar {
      @include useTheme {
        background-color: getTheme('sv-background-highlight-color');
      }
    }
  }
}

.swiper-data {
  width: 100%;
  height: 100%;

  &.animation {
    transition: transform 0.5s linear;
    transform: scale(0.8);
  }

  &.active {
    transform: scale(1);
  }

  .image {
    width: 100%;
    height: 100%;
    border-radius: inherit;
  }
}
</style>